﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using YeaTrip.Framework.CookieSession;
using YeaTrip.Framework.Log;

namespace YeaTrip.Framework.VC
{
    /// <summary>
    /// Controller基类
    /// </summary>
    public class YeaTripController : Controller
    {
        /// <summary>
        /// 统一管理Cookie
        /// </summary>
        public YeaTripCookie YeaTripCookie
        {
            get
            {
                return new CookieSession.YeaTripCookie(Response, Request);
            }
        }

        /// <summary>
        /// 统一管理Session
        /// </summary>
        public YeaTripSession YeaTripSession
        {
            get
            {
                return new CookieSession.YeaTripSession(Session);
            }
        }

        /// <summary>
        /// 用户登录时的用户ID
        /// </summary>
        public string CustID
        {
            get
            {
                return Session["CustID"] as string;
            }
            set { Session["CustID"] = value; }
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            YeaTripLog.LogTrans(filterContext);
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            //获取发起异常，以获取可能的自定义异常
            Exception ex = filterContext.Exception;

            YeaTripLog.LogException(ex);

            ViewResult view = new ViewResult()
            {
                ViewName = "~/Views/Shared/Error.cshtml",
                //ViewData = new ViewDataDictionary<HandleErrorInfo>(new EWinException(null,filterContext.Exception)),
                //ViewData = new ViewDataDictionary<HandleErrorInfo>(new HandleErrorInfo(ex, filterContext.RouteData.Values["controller"] as string, filterContext.RouteData.Values["action"] as string)),
                

            };
            filterContext.HttpContext.Response.ClearContent();

            //当是异步调用时，返回500错误；否则返回错误页面
            if (filterContext.RequestContext.HttpContext.Request.Headers["X-Requested-With"] != null &&
                filterContext.RequestContext.HttpContext.Request.Headers["X-Requested-With"].Equals("XMLHttpRequest"))
            {
                filterContext.HttpContext.Response.StatusCode = 500;
            }
            else
            {
                filterContext.Result = view;
            }
            filterContext.ExceptionHandled = true;
        }

    }
}
